/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 *
 *
 *
 */
package rad.framework.search.service;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import rad.framework.jpa.EntityPersistenceContextMap;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.log.Log;
import org.jboss.seam.util.Reflections;

/**
 * Creates of a set of string's that contain the name of all the fields in all the
 * entities. 
 * */
@Name("rad.framework.search.service.searchMetaData")
@Scope(ScopeType.APPLICATION)
@Startup
public class SearchMetaData {
	@Logger
	Log log;
	
	private Set<String> fields = new TreeSet<String>();
	
	/**
	 * @return a set of string's that include all the different field names to search over.
	 * */
	public Set<String> getFields() {
		return fields;
	}
	
	@Observer("org.jboss.seam.postInitialization")
	/**
	 * Initializes the set of field names. It grabs all the entities and extracts all the 
	 * fields by parsing through all their getter methods. 
	 * */
	public void init(){
		Set<String> entities = EntityPersistenceContextMap.instance().getEntityNames();
		Class<?>[] classes = new Class[entities.size()];
		int i=0;
		
		try{
			for(String entity : entities){
				//converts the set of strings into an array of classes
				classes[i] = Reflections.classForName(entity);
				//if the class isn't indexed it isn't worth finding fields
				if(classes[i].isAnnotationPresent(Indexed.class)){		
					//gather the Getter methods to iterate over
					List<Method> getters = Reflections.getGetterMethods(classes[i], Field.class);
					//loop through the methods and grab the field names
					for(Method currMeth : getters) {
						String fieldName = currMeth.getAnnotation(Field.class).name();
						//if a name isn't explicitly defined, this will assign the
						//fieldName to whatever the X resolves to in getX()
						if(fieldName.equals("")){
							fieldName = currMeth.getName().substring(3).toLowerCase();
						}
						//add the field to the instance variable fields
						fields.add(fieldName);
					}
					i++;
				}
			}
		}catch(ClassNotFoundException cnfe){
			log.error("Class from Metadata cannot be found!");
			throw new RuntimeException(cnfe);
		}
		log.info("Finished intializing search meta data");
	}
	
	/**
	 * @return a string representation of the set of fields.
	 * */
	public String toString() {
		ToStringBuilder builder = new ToStringBuilder(this,
				ToStringStyle.MULTI_LINE_STYLE);
		Set<String> names = fields;
		builder.append("field list: ");
		for (String name : names) {
			builder.append(name);
		}
		return builder.toString();
	}
	
	/**
	 * @return the singleton instance of SearchMetaData.
	 * */
	public static SearchMetaData instance() {
		return (SearchMetaData) Component
				.getInstance(SearchMetaData.class);
	}
}